package com.yuhanginfo.common.utils;

import com.drew.metadata.*;
import com.drew.metadata.exif.*;
import com.drew.imaging.jpeg.*;
import com.drew.lang.*;
import java.io.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageGeo {
	private double lat = 0.0;
	private double lon = 0.0;
	private double alt = 0.0;
	private boolean error = false;
	private static Logger logger = LoggerFactory.getLogger(ImageGeo.class);

	public ImageGeo(String filename) {
		try {
			error = false;
			File jpegFile = new File(filename);
			Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);

			GpsDirectory gpsdir = (GpsDirectory) metadata
					.getDirectory(GpsDirectory.class);
			Rational [] latpart = gpsdir
					.getRationalArray(GpsDirectory.TAG_GPS_LATITUDE);
			Rational [] lonpart = gpsdir
					.getRationalArray(GpsDirectory.TAG_GPS_LONGITUDE);
			String northing = gpsdir
					.getString(GpsDirectory.TAG_GPS_LATITUDE_REF);
			String easting = gpsdir
					.getString(GpsDirectory.TAG_GPS_LONGITUDE_REF);

			try {
				alt = gpsdir.getDouble(GpsDirectory.TAG_GPS_ALTITUDE);
			} catch (Exception ex) {
				logger.debug(ex.getMessage(),ex);
			}

			double latsign = 1.0d;
			if ("S".equalsIgnoreCase(northing))
				latsign = -1.0d;
			double lonsign = 1.0d;
			if ("W".equalsIgnoreCase(easting))
				lonsign = -1.0d;
			lat = (Math.abs(latpart[0].doubleValue())
					+ latpart[1].doubleValue() / 60.0d + latpart[2]
					.doubleValue() / 3600.0d) * latsign;
			lon = (Math.abs(lonpart[0].doubleValue())
					+ lonpart[1].doubleValue() / 60.0d + lonpart[2]
					.doubleValue() / 3600.0d) * lonsign;

			if (Double.isNaN(lat) || Double.isNaN(lon))
				error = true;
		} catch (Exception ex) {
			logger.debug(ex.getMessage(),ex);
			error = true;
		}
	}

	public double getLat() {
		return lat;
	}

	public void setLat(double lat) {
		this.lat = lat;
	}

	public double getLon() {
		return lon;
	}

	public void setLon(double lon) {
		this.lon = lon;
	}

	public double getAlt() {
		return alt;
	}

	public void setAlt(double alt) {
		this.alt = alt;
	}

	public boolean isError() {
		return error;
	}

	public void setError(boolean error) {
		this.error = error;
	}
	
}
